// pages/swap/swap.js
const app = getApp()
import _ from './../../utils/lodash.js';
import util from './../../utils/util.js';
import config from './../../utils/config.js';

let permissions = [];
if (app.globalData.userInfo) {
    permissions = app.globalData.userInfo.permissions
}
const find = _.find;

function isNumericStart(str) {
    return /^\d/.test(str);
}

let EBOriginData = '';
let index = 0
Page({

    /**
     * 页面的初始数据
     */
    data: {
        step: 1,
        old_number: '',
        new_number: '',
        new_number_id: '',
        new_number_in_system: false,
        old_number_obj: {},
        new_number_obj: {},
        initial_value_1: '121',//水表底数
        initial_value_2: '',
        initial_value_3: '',
        initial_value_4: '',
        initial_value_5: '',
        initial_value_6: '',
        initial_value_7: '',
        initial_value_8: '',
        total_value_1: '',//累计充值水量
        total_value_2: '',
        total_value_3: '',
        total_value_4: '',
        total_value_5: '',
        total_value_6: '',
        total_value_7: '',
        total_value_8: '',
        display_value_1: '',//表盘数
        display_value_2: '',
        display_value_3: '',
        display_value_4: '',
        display_value_5: '',
        display_value_6: '',
        display_value_7: '',
        display_value_8: '',
        pay_value_1: '',//充值水量
        pay_value_2: '',
        pay_value_3: '',
        pay_value_4: '',
        pay_value_5: '',
        pay_value_6: '',
        pay_value_7: '',
        pay_value_8: '',
        portsArr:[],
        portArr: [],
        connected: false,
        serviceIds: [],
        logs: [],
        clearLogs: [],
        newDisplayLogs: [],
        newDisplayValueLogs: [],
        payValueLogs: [],
        clearSuccessPort: 1,
        clear: false,
        pay: false,
        newDisplayValueSuccessPort: 1,
        newDisplayValueSuccessPortIndex: 0,
        payValueSuccessPort: 0,
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        const that = this
        this.changeTitle();
        wx.onBLEConnectionStateChange(function (res) {
            // 该方法回调中可以用于处理连接意外断开等异常情况
            console.log(`device ${res.deviceId} state has changed, connected: ${res.connected}`)
            that.setData({
                connected: res.connected
            }, function () {
                if (res.connected) {
                    this.getBLEDeviceServices(that.data.deviceId)
                } else {
                    util.toastError('蓝牙连接已断开')
                }
            })
        })
    },
    bindble: function () {
        console.log('bindble')
        this.stopBluetoothDevicesDiscovery()
        index = 0
        this.openBluetoothAdapter()
    },
    openBluetoothAdapter() {
        //util.toastError('请先打开蓝牙');
        console.log('openBluetoothAdapter')
        wx.openBluetoothAdapter({
            success: (res) => {
                console.log('openBluetoothAdapter success', res)
                this.startBluetoothDevicesDiscovery()
            },
            fail: (res) => {
                console.log('openBluetoothAdapter fail', res)
                util.toastError('请先打开蓝牙' + res.errCode);
                if (res.errCode === 10001) {
                    console.log('请先打开蓝牙1') //当蓝牙开关未开启或手机不支持蓝牙时，会返回错误 (errCode=10001)。
                    // util.toastError('10001');
                    wx.onBluetoothAdapterStateChange(function (res) {
                        console.log('onBluetoothAdapterStateChange', res)
                        if (res.available) {
                            this.startBluetoothDevicesDiscovery()
                        }
                    })
                }
            }
        })
    },
    startBluetoothDevicesDiscovery() {
        // if (this._discoveryStarted) {
        //   return
        // }
        // this._discoveryStarted = true
        wx.showLoading({
            title: '蓝牙连接中...',
        })
        wx.startBluetoothDevicesDiscovery({
            allowDuplicatesKey: true,
            success: (res) => {
                console.log('startBluetoothDevicesDiscovery success', res)
                this.onBluetoothDeviceFound()
            },
        })
    },
    onBluetoothDeviceFound() {
        const that = this
        wx.onBluetoothDeviceFound((res) => {
            console.log('onBluetoothDeviceFound res', res)
            res.devices.forEach(device => {
                if (!device.name && !device.localName) {
                    return
                }
                if (!isNumericStart(device.name || device.localName)) {
                    return
                }
                let bleName = device.name ? device.name : device.localName;
                console.log('bleName', bleName)
                if (bleName.indexOf(that.data.new_number) >= 0 && index === 0) {
                    index++
                    this.stopBluetoothDevicesDiscovery()
                    this.setData({
                        bleName: bleName,
                        deviceId: device.deviceId
                    }, function () {
                        this.createBLEConnection()
                    })
                }


            })
        })
    },
    createBLEConnection() {
        const that = this;
        console.log('createBLEConnection')
        this.setData({
            loading: true,
        })

        wx.getBLEMTU({
            deviceId: this.data.deviceId,
            writeType: 'write',
            success(res) {
                console.log('getBLEMTU')
                console.log(res)
            }
        })
        wx.createBLEConnection({
            deviceId: this.data.deviceId,
            success: (res) => {
                wx.hideLoading()
                util.toastError('连接成功');
                console.log("createBLEConnection success")
                this.setData({
                    connected: true,
                    loading: false,
                }, function () {
                    console.log('连接成功得ID,', that.data.deviceId)
                    that.getBLEDeviceServices(that.data.deviceId)
                })

                wx.setBLEMTU({
                    deviceId: this.data.deviceId,
                    mtu: 256,
                    success: (res) => {
                        console.log('设置MTU256成功')
                    },
                    fail: (res) => {
                        console.log('设置MTU失败')
                        console.log(res)
                    },
                })


            },
            fail: (res) => {
                util.bleErrCode(res.errCode);
                console.log('连接失败')
                console.log(res)
                if (res.errCode === -1) {
                    this.setData({
                        connected: true,
                        loading: false,
                    })
                } else {
                    this.setData({
                        loading: false,
                    })
                }

            }
        })

    },
    getBLEDeviceServices(deviceId) {
        const that = this
        wx.getBLEDeviceServices({
            deviceId: this.data.deviceId,
            success: (res) => {
                console.log('所有服务', res.services)
                let serviceIds = [];
                for (let i = 0; i < res.services.length; i++) {

                    //安卓上，部分机型获取设备服务时会多出 00001800 和 00001801 UUID 的服务，这是系统行为，注意不要使用这两个服务。
                    if (res.services[i].uuid.indexOf('00001800') >= 0 || res.services[i].uuid.indexOf('00001801') >= 0) {
                        console.log(`res.services[i].uuid ${res.services[i].uuid} 是系统行为，不要使用`)
                    } else {
                        console.log('res.services[i].uuid', res.services[i].uuid)
                        serviceIds.push(res.services[i].uuid)

                    }

                }
                this.setData({
                    serviceIds: serviceIds
                }, function () {
                    for (let i = 0; i < this.data.serviceIds.length; i++) {
                        setTimeout(function () {
                            that.getBLEDeviceCharacteristics(deviceId, that.data.serviceIds[i])
                        }, 100)

                    }
                })
            }
        })
    },

    getBLEDeviceCharacteristics(deviceId, serviceId) {
        const that = this;
        wx.getBLEDeviceCharacteristics({
            deviceId,
            serviceId,
            success: (res) => {
                console.log('getBLEDeviceCharacteristics success', res.characteristics)
                let findWrite = find(res.characteristics, function (o) {
                    return o.properties.write
                })
                let findNotify = find(res.characteristics, function (o) {
                    return o.properties.notify
                })


                if (findWrite && findNotify) {

                    this.setData({
                        selectServerChars: {
                            deviceId: deviceId,
                            serviceId: serviceId,
                            writeCharUUID: findWrite.uuid,
                            notifyCharUUID: findNotify.uuid,
                        }
                    }, function () {
                        this.recvBLECharacterNotice(deviceId, serviceId, this.data.selectServerChars.notifyCharUUID);
                        this.writeLogs(`发现服务${JSON.stringify(this.data.selectServerChars)}`, 'rgb(232,137,60)')
                        // this.handleSendE0()
                    })

                }


            },
            fail(res) {
                console.log('serviceId 出错了', serviceId)
                console.error('getBLEDeviceCharacteristics', res)
                util.bleErrCode(res.errCode);
                that.writeLogs(util.bleErrCode(res.errCode), 'red')
            }
        })
        //监听蓝牙低功耗设备的特征值变化事件。必须先调用 wx.notifyBLECharacteristicValueChange 接口才能接收到设备推送的 notification。
        wx.onBLECharacteristicValueChange((characteristic) => {
            console.log(characteristic.value)

        })
    },
    getName: function (name) {
        let n1 = name.substr(0, 2)
        let n2 = name.substr(2, 2)
        let n3 = name.substr(4, 2)
        let n4 = name.substr(6, 2)
        return `${n4} ${n3} ${n2} ${n1}`
    },
    handleSendEB: function () {
        console.log('this.getName()', this.getName(this.data.new_number))
        let str = `0E ${this.getName(this.data.new_number)} 00 EB`
        let sendHex = '68 ' + str + ' ' + util.calc(str) + ' 16'
        console.log('sendHex', sendHex)
        this.writeLogs(`下发数据：${sendHex}`, 'orange');
        this.writeBLECharacteristicValue(sendHex)
    },
    handleSendE6: function (port) {
        let str = `0E ${this.getName(this.data.new_number)} 00 E6 ${port}`
        let sendHex = '68 ' + str + ' ' + util.calc(str) + ' 16'
        console.log('sendHex', sendHex)
        this.writeLogs(`下发数据：${sendHex}`, 'orange');
        this.writeBLECharacteristicValue(sendHex)
    },
    handleSend85: function (port, value) {
        if (!this.data[`display_value_${Number(port)}`]) {
            util.toastError(`端口${port}表盘数不能为空`)
            return false
        }
        let input1 = util.padWithZeros(parseInt(Number(this.data[`display_value_${Number(port)}`]) * 1000), 8, '0')
        console.log('input1', input1)
        let str = `0E ${this.getName(this.data.new_number)} 00 85 ${port} ${input1.substr(6, 2)} ${input1.substr(4, 2)} ${input1.substr(2, 2)} ${input1.substr(0, 2)} 2C`

        let sendHex = '68 ' + str + ' ' + util.calc(str) + ' 16'
        console.log('sendHex', sendHex)
        this.writeLogs(`下发数据：${sendHex}`, 'orange');
        this.writeBLECharacteristicValue(sendHex)
    },
    decToHex: function (number) {
        return (parseInt(number, 10) >>> 0).toString(16).toLocaleUpperCase();
    },
    handleSend86: function (port) {
        //    initial_value_1:'1',//水表底数      total_value_1:'2',//累计充值水量  display_value_1:'',//表盘数
        if (!(this.data[`initial_value_${Number(port)}`].toString())) {
            util.toastError(`端口${port}水表底数不能为空`)
            console.log(`端口${port}水表底数不能为空`)
            return false
        }
        if (!(this.data[`total_value_${Number(port)}`].toString())) {
            util.toastError(`端口${port}累计充值水量不能为空`)
            console.log(`端口${port}累计充值水量不能为空`)
            return false
        }
        if (!(this.data[`display_value_${Number(port)}`].toString())) {
            util.toastError(`端口${port}表盘数不能为空`)
            return false
        }
        //用户总充值水量 - （当前水表表盘数 - 旧表底数）
        let value = Number(this.data[`total_value_${Number(port)}`]) - (Number(this.data[`display_value_${Number(port)}`]) - Number(this.data[`initial_value_${Number(port)}`]))
        this.setData({
            [`pay_value_${Number(port)}`]: Number(Math.round(value * 1000) / 1000)
        })
        // if(Number(value)===0){
        //     console.log(`端口${port}需下发充值水量为0，不下发指令`)
        //     util.toastError(`端口${port}需下发充值水量为0，不下发指令`);
        //     this.writeLogs(`端口${port}需下发充值水量为0，不下发指令`, 'orange');
        //     return
        // }

        let str = ''
        let input1 = ''
        let input2 = util.padWithZeros(Number(1).toString(16), 4, '0') //第一次
        console.log('input1', input1)
        if (Number(value) >= 0) {
            console.log('大于0')
            input1 = util.padWithZeros(parseInt(Number(Math.round(value * 1000) / 1000) * 1000).toString(16), 8, '0')
            console.log('input1', input1)
            str = `0E ${this.getName(this.data.new_number)} 00 86 ${port} ${input1.substr(6, 2)} ${input1.substr(4, 2)} ${input1.substr(2, 2)} ${input1.substr(0, 2)} ${input2.substr(2, 2)} ${input2.substr(0, 2)} 00 00`

        } else if (Number(value) < 0) {
            console.log('小于0')
            input1 = this.decToHex(Number(Math.round(value * 1000) / 1000) * 1000)
            console.log('input1', input1)
            str = `0E ${this.getName(this.data.new_number)} 00 86 ${port} ${input1.substr(6, 2)} ${input1.substr(4, 2)} ${input1.substr(2, 2)} ${input1.substr(0, 2)} ${input2.substr(2, 2)} ${input2.substr(0, 2)} 00 00`
        }

        let sendHex = '68 ' + str + ' ' + util.calc(str) + ' 16'
        console.log('sendHex', sendHex)
        this.writeLogs(`下发数据：${sendHex}`, 'orange');
        this.writeBLECharacteristicValue(sendHex)
    },
    handleSendE0: function () { //请求上线

        let str = `0E ${this.getName(this.data.new_number)} 00 E0`
        let sendHex = '68 ' + str + ' ' + util.calc(str) + ' 16'
        console.log('sendHex', sendHex)
        this.writeLogs(`下发数据：${sendHex}`, 'orange');
        this.writeBLECharacteristicValue(sendHex)
    },
    writeBLECharacteristicValue(sendHex) {
        const that = this
        // if (sendHex.substr(21, 2) === 'E6'&&that.data.step===3){
        //   console.log(`端口${sendHex.substr(23, 2)}清零完成`)
        //   that.writeClearLogs(`端口${sendHex.substr(23, 2)}清零指令下发完成`, 'orange');
        // }

        if (!this.data.connected) {
            util.toastError('请先连接设备');
            return false
        }
        var typedArray = new Uint8Array(sendHex.match(/[\dA-F]{2}/gi).map(function (h) {
            return parseInt(h, 16)
        }))
        // console.log(typedArray)

        var writeValue = typedArray.buffer
        wx.writeBLECharacteristicValue({
            deviceId: this.data.selectServerChars.deviceId,
            serviceId: this.data.selectServerChars.serviceId,
            characteristicId: this.data.selectServerChars.writeCharUUID,
            value: writeValue,
            success(res) {
                // that.writeLogs("下发数据成功: " + sendHex, 'green');
                // console.log(sendHex.substr(12, 2))
                // 68 0E 68 57 89 76 00 89 01 00 00
                // console.log(sendHex)
                if (sendHex.substr(21, 2) === 'E6' && Number(that.data.step) === 3) {
                    that.writeClearLogs(`下发数据：${sendHex}`, 'orange');
                }
                if (sendHex.substr(21, 2) === 'E0' && Number(that.data.step) === 3) {
                    that.writeClearLogs(`下发数据：${sendHex}`, 'orange');
                }
                if (sendHex.substr(21, 2) === 'E0' && Number(that.data.step) === 4) {
                    that.writeNewDisplayLogs(`下发数据：${sendHex}`, 'orange');
                }

                if (sendHex.substr(21, 2) === '85' && Number(that.data.step) === 4) {//返回的指令没有端口
                    that.writeNewDisplayLogs(`下发数据：${sendHex}`, 'orange');
                }

                if (sendHex.substr(21, 2) === 'E0' && Number(that.data.step) === 5) {
                    that.writePayValueLogs(`${sendHex}`, 'orange');
                    // that.writePayValueLogs(`请求上线指令下发成功`, 'green');
                }
                if (sendHex.substr(21, 2) === '86' && Number(that.data.step) === 5) {//返回的指令没有端口
                    that.writePayValueLogs(`下发数据：${sendHex}`, 'orange');
                }

            },
            fail: function (res) {
                console.log(res);
                that.writeLogs("下发数据失败: " + res.errCode, 'red');
                util.bleErrCode(res.errCode);
            }
        })
    },

    recvBLECharacterNotice: function (deviceId, serviceId, charId) {
        //接收设置是否成功
        this.writeLogs("注册Notify服务");
        var that = this;
        wx.notifyBLECharacteristicValueChange({
            deviceId: deviceId,
            serviceId: serviceId,
            characteristicId: charId,
            state: true, //启用Notify功能
            success: function (res) {
                wx.onBLECharacteristicValueChange(function (res) {
                    console.log(res);
                    that.writeLogs("收到Notify数据: " + util.addSpaceEveryTwoChars(util.ab2hex(res.value)));
                    let notifyData = util.ab2hex(res.value)
                    console.log('notifyData', notifyData)
                    if (notifyData.substr(14, 2) === 'e0') {
                        if (notifyData.substr(16, 2) === '00') {
                            that.writeClearLogs(`请求上线指令下发成功`, 'green');
                            if (that.data.step === 3) {
                                setTimeout(function () {
                                    wx.hideLoading()
                                    that.setData({
                                        clear: true
                                    })
                                }, 10000)
                            }
                            if (that.data.step === 4) {
                                setTimeout(function () {
                                    wx.hideLoading()
                                    that.writeNewDisplayLogs(`请求上线指令下发成功`, 'green');
                                    that.setData({
                                        newValue: true
                                    })
                                }, 10000)
                            }
                            if (that.data.step === 5) {
                                that.writePayValueLogs(`请求上线指令下发成功`, 'green');
                                setTimeout(function () {
                                    wx.hideLoading()
                                    that.writePayValueLogs(`换表完成`, 'green');
                                    that.writePayValueLogs(`请在系统删除旧集中器`, 'green');
                                    util.toastError('换表完成,请在系统删除旧集中器')
                                    that.setData({
                                        pay: true
                                    })
                                    // that.resetOldConstrator()
                                }, 10000)
                            }
                        } else {
                            util.toastError(`请求上线指令下发失败`, 'red');
                        }

                    }
                    if (that.data.step === 3 && notifyData.substr(14, 2) === 'e6') {
                        if (notifyData.substr(16, 2) === '00') {
                            let clearSuccessPort = that.data.clearSuccessPort
                            that.writeClearLogs(`端口0${clearSuccessPort}清零指令下发成功`, 'green');
                            if (clearSuccessPort < 8) {
                                that.setData({
                                    clearSuccessPort: clearSuccessPort + 1
                                }, function () {
                                    setTimeout(function () {
                                        that.handleSendE6(`0${that.data.clearSuccessPort}`)
                                    }, 5000)

                                })

                            }
                            if (clearSuccessPort === 8) {
                                if (that.data.new_number_in_system) {
                                    //新采集已经存在于系统，修改采集器
                                    console.log('新采集已经存在于系统，修改采集器')
                                    that.editConctrator(true)
                                } else {
                                    //向系统添加新采集器
                                    console.log('向系统添加新采集器')
                                    that.addConctrator()
                                }

                            }
                        } else {
                            that.writeClearLogs(`清零指令下发失败`, 'red');
                        }
                    }

                    if (notifyData.substr(14, 2) === '85' && Number(that.data.step) === 4) {//返回的指令没有端口
                        if (notifyData.substr(16, 2) === '00') {
                            let newDisplayValueSuccessPortIndex = that.data.newDisplayValueSuccessPortIndex
                            that.writeNewDisplayLogs(`端口${that.data.portArr[newDisplayValueSuccessPortIndex]}设表盘数指令下发成功`, 'green');
                            if (newDisplayValueSuccessPortIndex < that.data.portArr.length - 1) {
                                that.setData({
                                    newDisplayValueSuccessPortIndex: newDisplayValueSuccessPortIndex + 1
                                }, function () {
                                    let newDisplayValueSuccessPortIndex = that.data.newDisplayValueSuccessPortIndex
                                    setTimeout(function () {
                                        that.handleSend85(`0${that.data.portArr[newDisplayValueSuccessPortIndex]}`)
                                    }, 5000)

                                })

                            } else {
                                that.editConctrator()
                            }

                        } else {
                            that.writeNewDisplayLogs(`设表盘数指令下发失败`, 'red')
                        }

                    }
                    if (that.data.step === 5 && notifyData.substr(14, 2) === '86') {
                        let payValueSuccessPort = that.data.payValueSuccessPort
                        if (notifyData.substr(16, 2) === '00') {
                            that.writePayValueLogs(`端口${that.data.portArr[payValueSuccessPort]}充值水量指令下发完成`, 'green');

                            if (payValueSuccessPort < that.data.portArr.length - 1) {
                                that.setData({
                                    payValueSuccessPort: payValueSuccessPort + 1
                                }, function () {
                                    let payValueSuccessPort = that.data.payValueSuccessPort
                                    setTimeout(function () {
                                        that.handleSend86(`0${that.data.portArr[payValueSuccessPort]}`)
                                    }, 5000)

                                })

                            } else {
                                setTimeout(function () {
                                    that.setPsn(1, that.handleSendE0)
                                }, 5000)

                            }
                        } else {
                            that.writePayValueLogs(`端口${that.data.portArr[payValueSuccessPort]}充值水量失败,失败代码为:${notifyData.substr(16, 2)}`, 'red');
                        }


                    }

                    if (that.data.step === 6 &&notifyData.substr(14, 2).toUpperCase() !== 'E0' &&notifyData.substr(14, 2).toUpperCase() !== '86') {
                        console.log('notifyData.length', notifyData.length)
                        if (EBOriginData.length !== 610) {
                            EBOriginData = EBOriginData + notifyData
                        }
                        if (EBOriginData.length === 610) {
                            notifyData = EBOriginData
                            console.log(notifyData)
                            let portsArr = []
                            for (let i = 0; i < 8; i++) {
                                let portsData = {}
                                portsData[`d${14}`] = parseInt(`${notifyData.substr(74 + 4 + i * 66, 2)}`, 16);
                                portsData[`d${15}`] = Number(`${notifyData.substr(82 + 4 + i * 66, 2)}${notifyData.substr(80 + 4 + i * 66, 2)}${notifyData.substr(78 + 4 + i * 66, 2)}${notifyData.substr(76 + 4 + i * 66, 2)}`)/1000;
                                portsData[`d${16}`] = Number(`${notifyData.substr(90 + 4 + i * 66, 2)}${notifyData.substr(88 + 4 + i * 66, 2)}${notifyData.substr(86 + 4 + i * 66, 2)}${notifyData.substr(84 + 4 + i * 66, 2)}`)/1000;
                                portsData[`d${17}`] = Number(`${notifyData.substr(98 + 4 + i * 66, 2)}${notifyData.substr(96 + 4 + i * 66, 2)}${notifyData.substr(94 + 4 + i * 66, 2)}${notifyData.substr(92 + 4 + i * 66, 2)}`)/1000;
                                portsData[`d${18}`] = Number(`${notifyData.substr(106 + 4 + i * 66, 2)}${notifyData.substr(104 + 4 + i * 66, 2)}${notifyData.substr(102 + 4 + i * 66, 2)}${notifyData.substr(100 + 4 + i * 66, 2)}`)/1000;
                                portsData[`d${19}`] = Number(`${notifyData.substr(114 + 4 + i * 66, 2)}${notifyData.substr(112 + 4 + i * 66, 2)}${notifyData.substr(110 + 4 + i * 66, 2)}${notifyData.substr(108 + 4 + i * 66, 2)}`)/1000;
                                portsData[`d${20}`] = parseInt(`${notifyData.substr(118 + 4 + i * 66, 2)}${notifyData.substr(116 + 4 + i * 66, 2)}`, 16);
                                portsData[`d${21}`] = Number(parseInt(`${notifyData.substr(126 + 4 + i * 66, 2)}${notifyData.substr(124 + 4 + i * 66, 2)}${notifyData.substr(122 + 4 + i * 66, 2)}${notifyData.substr(120 + 4 + i * 66, 2)}`, 16))/1000;
                                portsData[`d${22}`] = Number(util.hex2int(`${notifyData.substr(134 + 4 + i * 66, 2)}${notifyData.substr(132 + 4 + i * 66, 2)}${notifyData.substr(130 + 4 + i * 66, 2)}${notifyData.substr(128 + 4 + i * 66, 2)}`))/1000;
                                // portsData[`d${22}`]=parseInt(`${notifyData.substr(134+4+i*66,2)}${notifyData.substr(132+4+i*66,2)}${notifyData.substr(130+4+i*66,2)}${notifyData.substr(128+4+i*66,2)}`, 16);
                                portsData[`d${23}`] = parseInt(`${notifyData.substr(136 + 4 + i * 66, 2)}`, 16).toString(2).padStart(8, '0');
                                portsData[`d${231}`] = parseInt(`${notifyData.substr(136 + 4 + i * 66, 2)}`, 16).toString(2).padStart(8, '0').substring(6,8);
                                portsData[`d${232}`] = parseInt(`${notifyData.substr(136 + 4 + i * 66, 2)}`, 16).toString(2).padStart(8, '0').substring(5,6);
                                portsData[`d${233}`] = parseInt(`${notifyData.substr(136 + 4 + i * 66, 2)}`, 16).toString(2).padStart(8, '0').substring(4,5);
                                portsData[`d${234}`] = parseInt(`${notifyData.substr(136 + 4 + i * 66, 2)}`, 16).toString(2).padStart(8, '0').substring(3,4);
                                portsData[`d${235}`] = parseInt(`${notifyData.substr(136 + 4 + i * 66, 2)}`, 16).toString(2).padStart(8, '0').substring(2,3);
                                portsData[`d${236}`] = parseInt(`${notifyData.substr(136 + 4 + i * 66, 2)}`, 16).toString(2).padStart(8, '0').substring(1,2);
                                portsData[`d${237}`] = parseInt(`${notifyData.substr(136 + 4 + i * 66, 2)}`, 16).toString(2).padStart(8, '0').substring(0,1);
                                portsData[`d${24}`] = parseInt(`${notifyData.substr(138 + 4 + i * 66, 2)}`, 16).toString(2).padStart(8, '0');
                                portsData[`d${241}`] = parseInt(`${notifyData.substr(138 + 4 + i * 66, 2)}`, 16).toString(2).padStart(8, '0').substring(7,8);
                                portsData[`d${242}`] = parseInt(`${notifyData.substr(138 + 4 + i * 66, 2)}`, 16).toString(2).padStart(8, '0').substring(6,7);

                                console.log('portsData', portsData)
                                portsArr.push(portsData)
                            }
                            that.setData({
                                portsArr: portsArr,
                                EBdata: {
                                    d1: parseInt(`${notifyData.substr(16, 2)}`, 16),
                                    d2: notifyData.substr(30, 2) + notifyData.substr(28, 2) + "-" + notifyData.substr(26, 2) + "-" + notifyData.substr(24, 2) + " " + notifyData.substr(22, 2) + ":" + notifyData.substr(20, 2) + ":" + notifyData.substr(18, 2),
                                    d3: parseInt(`${notifyData.substr(32, 2)}`, 16),
                                    d4: parseInt(`${notifyData.substr(34, 2)}`, 16),
                                    d5: parseInt(`${notifyData.substr(36, 2)}`, 16),
                                    d6: util.hexToSignedInt(`${notifyData.substr(40, 2)}${notifyData.substr(38, 2)}`),
                                    d7: util.hexToSignedInt(`${notifyData.substr(40 + 4, 2)}${notifyData.substr(38 + 4, 2)}`),
                                    d8: util.hexToSignedInt(`${notifyData.substr(44 + 4, 2)}${notifyData.substr(42 + 4, 2)}`),
                                    d9: (`${notifyData.substr(52 + 4, 2)}${notifyData.substr(46 + 4, 2)}${notifyData.substr(48 + 4, 2)}${notifyData.substr(50 + 4, 2)}`),
                                    d10: parseInt(`${notifyData.substr(56 + 4, 2)}${notifyData.substr(54 + 4, 2)}`),
                                    d11: parseInt(`${notifyData.substr(60 + 4, 2)}${notifyData.substr(58 + 4, 2)}`, 16),
                                    d12: parseInt(`${notifyData.substr(64 + 4, 2)}${notifyData.substr(62 + 4, 2)}`, 16),
                                    d13: parseInt(`${notifyData.substr(72 + 4, 2)}${notifyData.substr(70 + 4, 2)}${notifyData.substr(68 + 4, 2)}${notifyData.substr(66 + 4, 2)}`, 16),

                                }
                            })
                        }

                    }


                });
            },
            fail: function (res) {
                console.log(res);
                that.writeLogs("接收数据失败: " + res.errCode, 'red');
                util.bleErrCode(res.errCode);
            }
        })
    },
    writeClearLogs(text, color) {
        var now = new Date();
        var hours = now.getHours();
        var minutes = now.getMinutes();
        var seconds = now.getSeconds();
        let clearLogs = this.data.clearLogs;
        clearLogs.unshift({
            color: color ? color : '#000',
            text: text,
            time: util.formatNumber(hours) + ':' + util.formatNumber(minutes) + ':' + util.formatNumber(seconds)
        })
        this.setData({
            clearLogs
        })
    },
    writeNewDisplayLogs(text, color) {
        var now = new Date();
        var hours = now.getHours();
        var minutes = now.getMinutes();
        var seconds = now.getSeconds();
        let newDisplayLogs = this.data.newDisplayLogs;
        newDisplayLogs.unshift({
            color: color ? color : '#000',
            text: text,
            time: util.formatNumber(hours) + ':' + util.formatNumber(minutes) + ':' + util.formatNumber(seconds)
        })
        this.setData({
            newDisplayLogs
        })
    },
    writePayValueLogs(text, color) {
        var now = new Date();
        var hours = now.getHours();
        var minutes = now.getMinutes();
        var seconds = now.getSeconds();
        let payValueLogs = this.data.payValueLogs;
        payValueLogs.unshift({
            color: color ? color : '#000',
            text: text,
            time: util.formatNumber(hours) + ':' + util.formatNumber(minutes) + ':' + util.formatNumber(seconds)
        })
        this.setData({
            payValueLogs
        })
    },
    writeLogs(text, color) {
        var now = new Date();
        var hours = now.getHours();
        var minutes = now.getMinutes();
        var seconds = now.getSeconds();
        let logs = this.data.logs;
        logs.unshift({
            color: color ? color : '#000',
            text: text,
            time: util.formatNumber(hours) + ':' + util.formatNumber(minutes) + ':' + util.formatNumber(seconds)
        })
        this.setData({
            logs
        })
    },
    closeBLEConnection() {
        const that = this
        wx.closeBLEConnection({
            deviceId: this.data.deviceId,
            success: (res) => {
                index = 0;
                console.log("closeBLEConnection success")
                util.toastError('断开连接成功');
                that.writeLogs('断开连接成功')
                that.setData({
                    connected: false
                })

            },
            fail: (res) => {
                that.writeLogs('断开连接失败')
                console.log('断开连接失败')
                util.bleErrCode(res.errCode);
                console.log(res)
            }
        })


    },
    stopBluetoothDevicesDiscovery() {
        wx.stopBluetoothDevicesDiscovery()

    },
    changeValue: function (e) {
        console.log('ds', e.currentTarget.dataset.item)
        console.log('value', e.detail.value)
        const item = e.currentTarget.dataset.item
        const name = e.currentTarget.dataset.name
        if (name === 'display_value') {
            this.setData({
                [`display_value_${item}`]: e.detail.value
            })
        }
    },
    changeOldNumber: function (e) {
        console.log('picker发送选择改变，携带值为', e.detail.value)
        this.setData({
            old_number: e.detail.value,
        })
    },
    changeNewNumber: function (e) {
        console.log('picker发送选择改变，携带值为', e.detail.value)
        this.setData({
            new_number: e.detail.value,
        })
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    scanPort: function (e) {
        console.log('ds', e.currentTarget.dataset.item)

        const item = e.currentTarget.dataset.item
        const that = this;
        wx.scanCode({
            scanType: 'barCode',
            success(res) {
                console.log(res)
                if (res.result.length !== 8) {
                    wx.showToast({
                        title: `条形码格式错误`,
                        icon: 'error'
                    })
                    return false
                }
                that.setData({
                    [`${item}_number`]: res.result
                })


            }
        })
    },
    handlejudge() {
        console.log(this.data.old_number)
        console.log(this.data.new_number)
        const that = this
        wx.request({
            url: `${config.prefix}/concentrator_check_exchange`,
            header: {
                Authorization: `Bearer ${app.globalData.userInfo.token}`
            },
            method: 'POST',
            data: {
                old_number: this.data.old_number,
                new_number: this.data.new_number,
            },
            success: function (res) {
                console.log('get res', res)
                if (res.statusCode === 200) {
                    if (res.data.data.pass === 1) {
                        wx.showToast({
                            title: `检测通过`,
                            icon: 'info'
                        })
                        that.setData({
                            step: 2
                        }, function () {
                            that.changeTitle()
                        })

                        that.fetOldConctratorValue()
                        that.fetOldConctrator()
                        that.fetNewConctratorExit()
                    } else {
                        util.toastError(res.data.data.message)

                    }

                } else {
                    util.converErrorCodeToMsg(res)
                }
            }
        })

    },
    addConctrator: function () {
        const that = this;

        wx.request({
            url: `${config.prefix}/concentrators`,
            header: {
                Authorization: `Bearer ${app.globalData.userInfo.token}`
            },
            method: 'POST',
            data: {
                number: that.data.new_number
            },
            success: function (res) {
                console.log('get res', res)
                if (res.statusCode === 200) {
                    that.writeClearLogs('添加集中器成功')
                    that.fetNewConctratorExit()
                    setTimeout(function () {
                        that.editConctrator(true)
                    }, 3000)

                } else {
                    util.converErrorCodeToMsg(res)
                }
            }
        })
    },
    editConctrator: function (init) {
        const that = this;
        const old_number_obj = this.data.old_number_obj;
        let sendData = {
            address: old_number_obj.address,
            remark: old_number_obj.remark,
            latitude: old_number_obj.latitude,
            longitude: old_number_obj.longitude,
            concentrator_images: [],
        };
        let meter_config = {}
        for (let i = 0; i <= this.data.portArr.length - 1; i++) {
            meter_config[`port${this.data.portArr[i]}`] = {
                meter_number: this.data[`port${this.data.portArr[i]}`],
                initial_value: init ? 0 : this.data[`display_value_${this.data.portArr[i]}`],
                caliber: "DN15",
                meter_images: []
            }
        }
        wx.request({
            url: `${config.prefix}/concentrators/${that.data.new_number_id}`,
            header: {
                Authorization: `Bearer ${app.globalData.userInfo.token}`
            },
            method: 'PUT',
            data: {
                ...sendData,
                config: {
                    platform:this.data.new_number_obj.config.platform,
                    meter_config: meter_config
                }
            },
            success: function (res) {
                console.log('get res', res)
                if (res.statusCode === 200) {
                    if (init) {
                        that.writeClearLogs('修改新集中器水表关系成功', 'green')
                    } else {
                        that.writeNewDisplayLogs('修改新集中器水表底数成功', 'green')
                    }

                    setTimeout(function () {
                        that.handleSendE0()
                    }, 10000)


                } else {
                    util.converErrorCodeToMsg(res)
                }
            }
        })
    },
    resetOldConstrator: function () {
        const that = this;
        const old_number_obj = this.data.old_number_obj;
        let sendData = {
            address: old_number_obj.address,
            remark: old_number_obj.remark,
            latitude: old_number_obj.latitude,
            longitude: old_number_obj.longitude,
            concentrator_images: old_number_obj.concentrator_images,
        };
        let meter_config = {}
        wx.request({
            url: `${config.prefix}/concentrators/${old_number_obj.id}`,
            header: {
                Authorization: `Bearer ${app.globalData.userInfo.token}`
            },
            method: 'PUT',
            data: {
                ...sendData,
                config: {
                    platform: old_number_obj.config.platform,
                    meter_config: meter_config
                }
            },
            success: function (res) {
                console.log('get res', res)
                if (res.statusCode === 200) {
                    that.writePayValueLogs(`旧集中器水表关系已清空`, 'green');
                    wx.hideLoading()
                } else {
                    util.converErrorCodeToMsg(res)
                }
            }
        })
    },
    fetNewConctratorExit: function () {
        const that = this;

        wx.request({
            url: `${config.prefix}/concentrators`,
            header: {
                Authorization: `Bearer ${app.globalData.userInfo.token}`
            },
            method: 'GET',
            data: {
                number: that.data.new_number
            },
            success: function (res) {
                console.log('get res', res)
                if (res.statusCode === 200) {
                    if (res.data.data.length === 1) {
                        console.log('新采集器已经存在系统')
                        that.setData({
                            new_number_in_system: true,
                            new_number_id: res.data.data[0].id,
                            new_number_obj: res.data.data[0]
                        })


                    }


                }
            }
        })
    },
    fetOldConctrator: function () {
        const that = this;

        wx.request({
            url: `${config.prefix}/concentrators`,
            header: {
                Authorization: `Bearer ${app.globalData.userInfo.token}`
            },
            method: 'GET',
            data: {
                number: that.data.old_number
            },
            success: function (res) {
                console.log('旧采集器 get res', res)
                if (res.statusCode === 200) {
                    if (res.data.data.length === 1) {
                        that.setData({
                            old_number_obj: res.data.data[0]
                        })


                    }


                }
            }
        })
    },

    fetOldConctratorValue: function (department) {
        const that = this;

        wx.request({
            url: `${config.prefix}/concentrator_info`,
            header: {
                Authorization: `Bearer ${app.globalData.userInfo.token}`
            },
            method: 'GET',
            data: {
                number: that.data.old_number
            },
            success: function (res) {
                console.log('get res', res)
                if (res.statusCode === 200) {
                    let data = res.data.data
                    console.log('data', data)
                    let meter_config = data
                    if (meter_config) {
                        console.log('meter_config', meter_config)
                        let portArr = []
                        for (let i in meter_config) {
                            let item = meter_config[i];
                            let index = i.substr(4, 1)
                            console.log('item', item)
                            portArr.push(Number(index))
                            that.setData({
                                [`port${index}`]: item.meter_number,
                                [`initial_value_${index}`]: item.initial_value,
                                [`total_value_${index}`]: item.cumulative_payment_volume,
                            }, function () {
                                console.log(that.data)
                            })
                        }
                        that.setData({
                            portArr
                        })

                    }


                }
            }
        })
    },
    setPsn: function (psn, cb) {
        const that = this;
        let items = []
        for (let i = 0; i < this.data.portArr.length; i++) {
            items.push({meter_number: that.data[`port${this.data.portArr[i]}`], psn: psn})
        }

        wx.request({
            url: `${config.prefix}/concentrator_psn`,
            header: {
                Authorization: `Bearer ${app.globalData.userInfo.token}`
            },
            method: 'POST',
            data: {
                items: items
            },
            success: function (res) {
                console.log('get res', res)
                if (res.statusCode === 200) {
                    console.log(`设置PSN为${psn}成功`)
                    that.writePayValueLogs(`设置PSN为${psn}成功`, 'green');
                    if (cb) {
                        setTimeout(function () {
                            cb()
                        }, 5000)
                    }
                } else {
                    util.converErrorCodeToMsg(res)
                }
            }
        })
    },

    handleClear() {
        const that = this

        wx.showModal({
            title: '提示',
            content: `是否重置该采集器`,
            success(res) {
                if (res.confirm) {
                    that.setData({
                        clearSuccessPort: 1,
                        clear: false,
                    }, function () {
                        wx.showLoading({
                            title: '勿离开本页面,预计需要1分钟...',
                        })
                        const clearSuccessPort = this.data.clearSuccessPort
                        that.handleSendE6(`0${clearSuccessPort}`)
                    })

                } else if (res.cancel) {
                    console.log('用户点击取消')
                }
            }
        })


    },
    handleNext(e) {
        console.log('ds', e.currentTarget.dataset.item)
        const item = e.currentTarget.dataset.item
        this.setData({
            step: Number(item)
        }, function () {
            if(this.data.step===4){
                const portArr=this.data.portArr
                for (let i = 0; i < portArr.length; i++) {
                    const port=portArr[i]
                    //用户总充值水量 - （当前水表表盘数 - 旧表底数）
                    let value = Number(this.data[`total_value_${Number(port)}`]) - (Number(this.data[`display_value_${Number(port)}`]) - Number(this.data[`initial_value_${Number(port)}`]))
                    this.setData({
                        [`pay_value_${Number(port)}`]:Number(Math.round(value * 1000) / 1000)
                    })
                }
            }
            if(this.data.step===6){
                this.handleSendEB()

            }
            this.changeTitle()
        })
    },
    handleConfirmOld() {
        const that = this;
        const portArr = this.data.portArr
        for (let i = 0; i < portArr.length; i++) {
            if (!this.data[`display_value_${portArr[i]}`]) {
                wx.showToast({
                    title: `端口${portArr[i]}表盘数必填`,
                    icon: 'error'
                })
                return false
            }
        }
        wx.showModal({
            title: '提示',
            content: `请确认旧集中器已拆下并已接上新集中器`,
            success(res) {
                if (res.confirm) {
                    console.log('用户点击确定');
                    that.setData({
                        step: 3
                    }, function () {
                        that.changeTitle()
                    })

                } else if (res.cancel) {
                    console.log('用户点击取消')
                }
            }
        })

    },

    handleNewValue() {
        const that = this;
        wx.showModal({
            title: '提示',
            content: `确认更新采集器表盘数据？`,
            success(res) {
                if (res.confirm) {
                    console.log('用户点击确定');
                    that.setData({
                        newDisplayValueSuccessPortIndex: 0,
                        newValue: false,
                    }, function () {
                        const newDisplayValueSuccessPortIndex = this.data.newDisplayValueSuccessPortIndex
                        wx.showLoading({
                            title: '勿离开本页面,预计需要1分钟...',
                        })
                        that.handleSend85(`0${that.data.portArr[newDisplayValueSuccessPortIndex]}`)
                    })
                } else if (res.cancel) {
                    console.log('用户点击取消')
                }
            }
        })

    },
    handlePayValue() {
        const that = this;
        wx.showModal({
            title: '提示',
            content: `确认更新采集器充值水量？`,
            success(res) {
                if (res.confirm) {
                    console.log('用户点击确定');
                    that.setData({
                        payValueSuccessPort: 0
                    }, function () {
                        // 用户总充值水量-（当前水表表盘数-旧表底数）
                        const payValueSuccessPort = this.data.payValueSuccessPort;
                        wx.showLoading({
                            title: '勿离开本页面,预计需要2分钟...',
                        })
                        that.handleSend86(`0${that.data.portArr[payValueSuccessPort]}`)
                    })
                } else if (res.cancel) {
                    console.log('用户点击取消')
                }
            }
        })

    },
    changeTitle() {
        if (this.data.step === 1) {
            wx.setNavigationBarTitle({
                title: '1.判断新旧集中器',
            })
        }
        if (this.data.step === 2) {
            wx.setNavigationBarTitle({
                title: '2.验证旧集中器信息',
            })
        }
        if (this.data.step === 3) {
            wx.setNavigationBarTitle({
                title: '3.重置新集中器',
            })
        }
        if (this.data.step === 4) {
            wx.setNavigationBarTitle({
                title: '4.更新表盘数据',
            })
        }
        if (this.data.step === 5) {
            wx.setNavigationBarTitle({
                title: '5.更新水表充值水量',
            })
        }
        if (this.data.step === 6) {
            wx.setNavigationBarTitle({
                title: '6.读取新采集器信息',
            })
        }
    },
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {
        console.log('item onUnload')
        EBOriginData=''
        this.stopBluetoothDevicesDiscovery()
        if (this.data.connected) {
            this.closeBLEConnection()
        }
    },


})